<template>
  <div class="repair-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>维修管理</h1>
      <el-button type="primary" @click="showAddRepairDialog">
        <el-icon><Plus /></el-icon>
        新增维修申请
      </el-button>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ pendingRepairs }}</div>
            <div class="stat-label">待处理维修</div>
            <div class="stat-icon pending"><el-icon><WarningFilled /></el-icon></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ inProgressRepairs }}</div>
            <div class="stat-label">进行中维修</div>
            <div class="stat-icon in-progress"><el-icon><Timer /></el-icon></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ completedRepairs }}</div>
            <div class="stat-label">已完成维修</div>
            <div class="stat-icon completed"><el-icon><Check /></el-icon></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ totalRepairs }}</div>
            <div class="stat-label">维修总数</div>
            <div class="stat-icon total"><el-icon><Tools /></el-icon></div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="searchQuery" placeholder="搜索维修编号/申请人/房产地址" prefix-icon="Search" />
          </el-col>
          <el-col :span="6">
            <el-select v-model="repairTypeFilter" placeholder="选择维修类型">
              <el-option label="全部类型" value="" />
              <el-option label="水电维修" value="water_electricity" />
              <el-option label="家具维修" value="furniture" />
              <el-option label="家电维修" value="appliance" />
              <el-option label="其他维修" value="other" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="statusFilter" placeholder="选择状态">
              <el-option label="全部状态" value="" />
              <el-option label="待处理" value="pending" />
              <el-option label="进行中" value="in_progress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 维修列表 -->
    <div class="repair-list-section">
      <el-card>
        <el-table :data="filteredRepairs" style="width: 100%" height="500px">
          <el-table-column prop="id" label="维修编号" width="120" />
          <el-table-column prop="propertyInfo" label="房产信息" />
          <el-table-column prop="applicant" label="申请人" width="120" />
          <el-table-column prop="contact" label="联系电话" width="120" />
          <el-table-column prop="repairType" label="维修类型" width="120">
            <template #default="scope">
              {{ getRepairTypeText(scope.row.repairType) }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="问题描述" show-overflow-tooltip />
          <el-table-column prop="submitTime" label="提交时间" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="showRepairDetail(scope.row)">查看详情</el-button>
              <el-button v-if="scope.row.status === 'pending'" type="success" link @click="startRepair(scope.row.id)">开始维修</el-button>
              <el-button v-if="scope.row.status === 'in_progress'" type="success" link @click="completeRepair(scope.row.id)">完成维修</el-button>
              <el-button type="danger" link @click="confirmCancelRepair(scope.row.id)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredRepairs.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增维修申请对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="房产信息">
          <el-input v-model="formData.propertyInfo" placeholder="请输入房产信息" />
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="formData.applicant" placeholder="请输入申请人姓名" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="formData.contact" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="维修类型">
          <el-select v-model="formData.repairType" placeholder="请选择维修类型">
            <el-option label="水电维修" value="water_electricity" />
            <el-option label="家具维修" value="furniture" />
            <el-option label="家电维修" value="appliance" />
            <el-option label="其他维修" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请详细描述维修问题" />
        </el-form-item>
        <el-form-item label="紧急程度" v-if="!isEditMode">
          <el-select v-model="formData.priority" placeholder="请选择紧急程度">
            <el-option label="一般" value="normal" />
            <el-option label="紧急" value="urgent" />
            <el-option label="非常紧急" value="very_urgent" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 维修详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="维修详情"
      width="700px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="维修编号">{{ selectedRepair.id }}</el-descriptions-item>
        <el-descriptions-item label="房产信息">{{ selectedRepair.propertyInfo }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{ selectedRepair.applicant }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ selectedRepair.contact }}</el-descriptions-item>
        <el-descriptions-item label="维修类型">{{ getRepairTypeText(selectedRepair.repairType) }}</el-descriptions-item>
        <el-descriptions-item label="问题描述">{{ selectedRepair.description }}</el-descriptions-item>
        <el-descriptions-item label="紧急程度">{{ getPriorityText(selectedRepair.priority) }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ selectedRepair.submitTime }}</el-descriptions-item>
        <el-descriptions-item label="处理人" v-if="selectedRepair.handler">{{ selectedRepair.handler }}</el-descriptions-item>
        <el-descriptions-item label="开始时间" v-if="selectedRepair.startTime">{{ selectedRepair.startTime }}</el-descriptions-item>
        <el-descriptions-item label="完成时间" v-if="selectedRepair.completeTime">{{ selectedRepair.completeTime }}</el-descriptions-item>
        <el-descriptions-item label="维修结果" v-if="selectedRepair.result">{{ selectedRepair.result }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ getStatusText(selectedRepair.status) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Plus, Tools, Check, WarningFilled, Timer } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 状态管理
const repairs = ref([])
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref({})
const selectedRepair = ref({})
const isEditMode = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')
const repairTypeFilter = ref('')
const statusFilter = ref('')

// 统计数据
const pendingRepairs = computed(() => repairs.value.filter(item => item.status === 'pending').length)
const inProgressRepairs = computed(() => repairs.value.filter(item => item.status === 'in_progress').length)
const completedRepairs = computed(() => repairs.value.filter(item => item.status === 'completed').length)
const totalRepairs = computed(() => repairs.value.length)

// 筛选后的维修列表
const filteredRepairs = computed(() => {
  let filtered = repairs.value
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(item => 
      item.id.toLowerCase().includes(query) ||
      item.applicant.toLowerCase().includes(query) ||
      item.propertyInfo.toLowerCase().includes(query)
    )
  }
  
  // 类型筛选
  if (repairTypeFilter.value) {
    filtered = filtered.filter(item => item.repairType === repairTypeFilter.value)
  }
  
  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(item => item.status === statusFilter.value)
  }
  
  // 按提交时间倒序排序
  filtered.sort((a, b) => new Date(b.submitTime) - new Date(a.submitTime))
  
  return filtered
})

// 初始化数据
onMounted(() => {
  initMockData()
})

// 初始化模拟数据
function initMockData() {
  repairs.value = [
    {
      id: 'RP2024001',
      propertyInfo: '1号楼 302室',
      applicant: '张三',
      contact: '13812345678',
      repairType: 'water_electricity',
      description: '卫生间漏水严重，需要紧急维修',
      priority: 'urgent',
      submitTime: '2024-01-15 14:30:00',
      status: 'pending'
    },
    {
      id: 'RP2024002',
      propertyInfo: '2号楼 501室',
      applicant: '李四',
      contact: '13987654321',
      repairType: 'furniture',
      description: '卧室衣柜门损坏，无法正常开关',
      priority: 'normal',
      submitTime: '2024-01-14 09:15:00',
      status: 'in_progress',
      handler: '王师傅',
      startTime: '2024-01-14 10:00:00'
    },
    {
      id: 'RP2024003',
      propertyInfo: '3号楼 203室',
      applicant: '王五',
      contact: '13756789012',
      repairType: 'appliance',
      description: '空调不制冷，需要检查维修',
      priority: 'urgent',
      submitTime: '2024-01-13 16:45:00',
      status: 'completed',
      handler: '刘师傅',
      startTime: '2024-01-13 17:00:00',
      completeTime: '2024-01-13 18:30:00',
      result: '制冷剂不足，已添加制冷剂并清理了空调滤网'
    },
    {
      id: 'RP2024004',
      propertyInfo: '1号楼 804室',
      applicant: '赵六',
      contact: '13698765432',
      repairType: 'other',
      description: '门锁需要更换，钥匙丢失',
      priority: 'very_urgent',
      submitTime: '2024-01-15 08:20:00',
      status: 'pending'
    },
    {
      id: 'RP2024005',
      propertyInfo: '2号楼 1102室',
      applicant: '钱七',
      contact: '13589012345',
      repairType: 'water_electricity',
      description: '厨房水龙头滴水，需要更换',
      priority: 'normal',
      submitTime: '2024-01-12 11:30:00',
      status: 'completed',
      handler: '张师傅',
      startTime: '2024-01-12 14:00:00',
      completeTime: '2024-01-12 14:30:00',
      result: '已更换新的水龙头'
    }
  ]
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    pending: '待处理',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
function getStatusType(status) {
  const typeMap = {
    pending: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取维修类型文本
function getRepairTypeText(type) {
  const typeMap = {
    water_electricity: '水电维修',
    furniture: '家具维修',
    appliance: '家电维修',
    other: '其他维修'
  }
  return typeMap[type] || type
}

// 获取优先级文本
function getPriorityText(priority) {
  const priorityMap = {
    normal: '一般',
    urgent: '紧急',
    very_urgent: '非常紧急'
  }
  return priorityMap[priority] || priority
}

// 显示新增维修对话框
function showAddRepairDialog() {
  isEditMode.value = false
  dialogTitle.value = '新增维修申请'
  formData.value = {
    propertyInfo: '',
    applicant: '',
    contact: '',
    repairType: '',
    description: '',
    priority: 'normal'
  }
  dialogVisible.value = true
}

// 提交表单
function submitForm() {
  if (isEditMode.value) {
    // 更新维修信息
    const index = repairs.value.findIndex(item => item.id === formData.value.id)
    if (index !== -1) {
      repairs.value[index] = { ...repairs.value[index], ...formData.value }
      ElMessage.success('维修信息更新成功')
    }
  } else {
    // 新增维修申请
    const newRepair = {
      ...formData.value,
      id: `RP${new Date().getFullYear()}${String(repairs.value.length + 1).padStart(3, '0')}`,
      submitTime: new Date().toLocaleString('zh-CN'),
      status: 'pending'
    }
    repairs.value.unshift(newRepair)
    ElMessage.success('维修申请添加成功')
  }
  dialogVisible.value = false
}

// 显示维修详情
function showRepairDetail(repair) {
  selectedRepair.value = { ...repair }
  detailDialogVisible.value = true
}

// 开始维修
function startRepair(id) {
  ElMessageBox.confirm('确定要开始维修吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const repair = repairs.value.find(item => item.id === id)
    if (repair) {
      repair.status = 'in_progress'
      repair.handler = '管理员'
      repair.startTime = new Date().toLocaleString('zh-CN')
      ElMessage.success('维修已开始')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 完成维修
function completeRepair(id) {
  ElMessageBox.prompt('请输入维修结果：', '完成维修', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请详细描述维修结果'
  }).then(({ value }) => {
    const repair = repairs.value.find(item => item.id === id)
    if (repair) {
      repair.status = 'completed'
      repair.result = value
      repair.completeTime = new Date().toLocaleString('zh-CN')
      ElMessage.success('维修已完成')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 确认取消维修
function confirmCancelRepair(id) {
  ElMessageBox.confirm('确定要取消这个维修申请吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger'
  }).then(() => {
    const repair = repairs.value.find(item => item.id === id)
    if (repair) {
      repair.status = 'cancelled'
      ElMessage.success('维修已取消')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 搜索处理
function handleSearch() {
  currentPage.value = 1
}

// 重置筛选条件
function resetFilters() {
  searchQuery.value = ''
  repairTypeFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
}

// 处理页码变化
function handleSizeChange(size) {
  pageSize.value = size
}

// 处理页面变化
function handleCurrentChange(current) {
  currentPage.value = current
}
</script>

<script>
export default {
  name: 'RepairManagementView'
}
</script>

<style scoped>
.repair-management-container {
  width: 100%;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 36px;
  opacity: 0.2;
}

.stat-icon.pending {
  color: #e6a23c;
}

.stat-icon.in-progress {
  color: #409eff;
}

.stat-icon.completed {
  color: #67c23a;
}

.stat-icon.total {
  color: #909399;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 20px;
}

/* 维修列表样式 */
.repair-list-section {
  margin-bottom: 20px;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>